﻿using System.Collections.Generic;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnEx
    {
        public static bool CopyBlendshapesVM(this SkinnedMeshRenderer Target, SkinnedMeshRenderer Source)
        {
            if (!Source || !Target) return false;
            var source = Source;
            var sourceMesh = source.sharedMesh;
            var target = Target;

            int[] mapping;
            float[] distance;
            Vector3[] vertices;
            Vector3[] normals;
            Vector4[] tangents;
            BoneWeight[] boneWeights;
            Blendshape[] blendshapes;

            if (!source.VertexMap(target, out mapping, out distance, out vertices, out normals, out tangents, out boneWeights, out blendshapes,
                null, null, null, null, null))
            {
                return false;
            }

            var mesh = target.CloneSharedMesh();
            var emptyDeltas = new Vector3[mesh.vertices.Length];
            var copyDeltas = true;

            for (int i = 0; i < blendshapes.Length; i++)
            {
                var shape = blendshapes[i];
                for (int ii = 0; ii < shape.frames.Count; ii++)
                {
                    var keyframe = shape.frames[ii];
                    var deltaVertices = copyDeltas ? keyframe.shapeDeltas : emptyDeltas;
                    var deltaNormals = copyDeltas ? keyframe.shapeNormals : null;
                    var deltaTangents = copyDeltas ? keyframe.shapeTangents : null;

                    mesh.AddBlendShapeFrame(shape.name, keyframe.frameWeight, deltaVertices, deltaNormals, deltaTangents);
                }
            }
            target.sharedMesh = mesh;
            return true;
        }
    }
}